import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const types = {
  SET_AUTHENTICATED: 'SET_AUTHENTICATED',
  SET_USER: 'SET_USER',
  SET_AVATAR: 'SET_AVATAR'
};

const state = {
  isAuthenticated: false,
  user: {},
  avatar: ''
};
const getters = {
  isAuthenticated: state => state.isAuthenticated,
  user: state => state.user,
  avatar: state => state.avatar
};
const mutations = {
  /**
   * [types.SET_AUTHENTICATED]里的是字符串，相当于funcName(){}函数/方法
   * */
  [types.SET_AUTHENTICATED](state, isAuthenticated) {
    if (isAuthenticated) state.isAuthenticated = isAuthenticated;
    else state.isAuthenticated = false;
  },
  [types.SET_USER](state, user) {
    if (user) state.user = user;
    else user = {};
  },
  [types.SET_AVATAR](state, avatar) {
    if (avatar) state.avatar = avatar;
    else avatar = null;
  }
};
const actions = {
  setAuthenticated: ({commit}, isAuthenticated) => {
    commit(types.SET_AUTHENTICATED, isAuthenticated);
  },
  setUser: ({commit}, user) => {
    commit(types.SET_USER, user);
  },
  setAvatar: ({commit}, avatar) => {
    commit(types.SET_AVATAR, avatar);
  },
  clearCurrentStore: ({commit}) => {
    commit(types.SET_AUTHENTICATED, false);
    commit(types.SET_USER, null);
    commit(types.SET_AVATAR, null);
  }
};

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
